<template>
  <div class="search-suggestion">
    <van-cell 
    v-for="(text, index) in suggestions" 
    :key="index" 
    icon="search"
    @click="$emit('search' , text )"
    >
    <span slot="title" v-html="highlight(text)"></span>
    </van-cell>
  </div>
</template>

<script>
import {getSearchSuggestions} from '@/api/search'

// 按需加载有好处   只会把使用到的成员打包到结果中
import { debounce } from 'lodash'

  export default {
    name: 'SearchSuggestion',
    components: {},
    props: {
        searchText: {
            type: String,
            required: true
        }
    },
    data() {
      return {
        suggestions: [], // 联想建议数据列表
        htmlStr: 'Hello <span style="color: red">World</span>'
        }
    },
    computed: {},
    watch: {
        searchText: {
            
            // debounce  函数
            //  返回防抖之后的函数
            handler: debounce( function (value) {
                this.loadSearchSuggestions(value)
            }, 1000),

            // 当 searchText 发生改变的时候会调用 handler
            // handler (val) {
            //     this.loadSearchSuggestions(val)
            // },
            immediate: true // 该回调将会在侦听开始之后被立即调用
        }
    },
    created() {},
    mounted() {},
    methods: {
        async loadSearchSuggestions (q) {
            try {
                const { data } = await getSearchSuggestions(q)
                this.suggestions = data.data.options
            } catch (err) {
                 this.$toast('获取失败')
            }
        },

        highlight(text) {
            const highlightStr = `<span class="active">${this.searchText}</span>`

            const reg = new RegExp(this.searchText, 'gi')
            return text.replace(reg, highlightStr)
            
        }
    }
  }
</script>

<style scoped lang="less">
    .search-suggestion {
        /deep/ span.active {
        color: #3296fa;
    }
    }
</style>
